﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Casamiel.API.Application.Commands;
using Casamiel.API.Application.Models;
using Casamiel.API.Application.Services;
using Casamiel.API.Infrastructure;
using Casamiel.API.Infrastructure.Filters;
using Casamiel.Application;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain;
using Casamiel.Domain.Entity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using MediatR;
using Casamiel.Domain.Response;
using Casamiel.Domain.Request;
using Casamiel.Domain.Response.IC;
using Casamiel.API.Application;
using Casamiel.Application.Commands;

namespace Casamiel.API.Controllers.V2
{
    /// <summary>
    /// 会员卡
    /// </summary>
    [Produces("application/json")]
    [ApiVersion("2.0")]
    [Route("api/v{api-version:apiVersion}/[controller]")]
	[TypeFilterAttribute(typeof(CheckTokenAttribute))]
	[Authorize]
	[ApiController]
    public class CardController : BaseController
    {
        private readonly IIcApiService _iicApiService;
        private readonly IMemberCardService _memberCard;
        private readonly IMobileCheckCode _mobileCheckCode;
        private readonly CasamielSettings _settings;
        //private readonly IUserLogService _userLog;
        private readonly NLog.ILogger logger = LogManager.GetLogger("IicApiService");
        private readonly IMemberService _memberService;
        private readonly IMediator _mediator;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="iicApiService"></param>
         /// <param name="memberCard"></param>
        /// <param name="mobileCheckCode"></param>
       
        /// <param name="memberService"></param>
        /// <param name="mediator"></param>
        public CardController(IOptionsSnapshot<CasamielSettings> settings,
            IIcApiService iicApiService,
            IMemberCardService memberCard,
            IMobileCheckCode mobileCheckCode,
           
             IMemberService memberService, IMediator mediator)
        {
            if (settings == null) {
                throw new ArgumentNullException(nameof(settings));
            }

            _settings = settings.Value;
            _iicApiService = iicApiService;
             _memberCard = memberCard;
            _mobileCheckCode = mobileCheckCode;
          
            _memberService = memberService;
            _mediator = mediator;
        }

        /// <summary>
        /// 我的会员券
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        ///<remarks>
        ///1、	返回数据内容：
        ///{"code":0,"msg":"处理成功",
        ///"content":"{"cardno":"xxx","phoneno":"xxx","wxopenid":"xxx",
        ///"tickets":[{"cardno":"卡号","ticketid":xxxx,"ticketname":"券名称","tickettype":"券类型","source":"券来源方式","state":1,"je":xxx.xx,"makedate","2016-01-08""startdate","2016-01-08""enddate","2016-10-08","prange":[{"pid":xxx,"count":xxx},{"pid":xxx,"count":xxx},……]},
        ///{"cardno":"xxxx","ticketid":xxxx,"ticketname":"周年庆券","tickettype":"充值赠送券","source":"微信","state":1,
        ///"je":xxx.xx,"makedate","2016-01-08""startdate","2016-01-08""enddate","2016-10-08","prange":[{"pid":xxx,"count":xxx},{"pid":xxx,"count":xxx},……]},……]}","sign":"9ade8ba90cf38745bea56398d235daae"}
        ///</remarks>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(ZmodelExt), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> GetTicticket([FromBody] GetTicticketReq data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            var hascard = await HasCard(token, data.Cardno).ConfigureAwait(false);
            if (!hascard) {
                return new JsonResult(new { code = -7, content = "", msg = "无此卡" });
            }
            var a = await _iicApiService.Geticticket(data).ConfigureAwait(false);



            var list = JsonConvert.DeserializeObject<TicketItemRoot>(a.content);
            return Ok(new { code = a.code, pageindex = a.pageindex, pagesize = a.pagesize, pagecount = a.pagecount, content = list });

            // return Ok(a);
        }

        /// <summary>
        /// 我的会员卡
        /// </summary>
        /// <param name="token">用户token必填</param>
        /// <returns></returns>

        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(BaseResult<List<CardInfoResponse>>), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<ActionResult<BaseResult<List<CardInfoResponse>>>> GetMyCard([FromHeader(Name = "u-token")] string token)
        {

            var mobile =  MemberHelper.GetMobile(token);
            var command = new GetMyCardCommand(mobile, base.LoginInfo.Item3) { RequestUrl = Request.GetShortUri(), UserIP = Request.GetUserIp() };
            var result = await _mediator.Send(command).ConfigureAwait(false);
            return result;
            #region MyRegion
            /*var list = await _memberCard.GetCardListAsyncByMobile<ICasaMielSession>(mobile).ConfigureAwait(false);

           //await _memberCard.GetCardListAsyncByMobile(mobile);
           var mycard = list.Where(a => a.IsBind == true);
           List<CardInfoResponse> cardlist = new List<CardInfoResponse>();
           foreach (var item in mycard)
           {
               var zmodel = await _iicApiService.GetCardBalance(item.CardNo).ConfigureAwait(false);
               var rnt = JsonConvert.DeserializeObject<JObject>(zmodel.content);
               if (zmodel.code == 0 || zmodel.code == 8)
               {
                   cardlist.Add(new CardInfoResponse
                   {
                       cardno = item.CardNo,
                       totalmoney = rnt == null ? "0" : rnt["totalmoney"].ToString(),
                       cardtype = item.CardType,
                       state = item.State.ToString(),
                       othermoney = rnt == null ? "0" : rnt["othermoney"].ToString(),
                       directmoney = rnt == null ? "0" : rnt["directmoney"].ToString(),
                       point = rnt == null ? "0" : rnt["point"].ToString()
                   });
               }
               else if (zmodel.code == 90)
               {
                   CardRefreshDto data = new CardRefreshDto { cardno = item.CardNo, phoneno = mobile, startdate = DateTime.Now.ToString("yyyy-MM-dd 00:00:00") };
                   var zmdel = await _iicApiService.icrefresh(data).ConfigureAwait(false);
                   logger.Trace($"CardRefresh:{JsonConvert.SerializeObject(zmdel)}");
                   if (zmdel.code == 0)
                   {
                       var jcard = JsonConvert.DeserializeObject<JObject>(zmdel.content);
                       //var mcard = await _memberCard.FindAsyncByCardnoMobile<ICasaMielSession>(item.CardNo, mobile);
                       var clist = await _memberCard.GetCardListAsyncByMobile<ICasaMielSession>(mobile).ConfigureAwait(false);
                       var mcard = clist.Where(c => c.CardType == "1" && c.IsBind == true).SingleOrDefault();
                       if (mcard != null)
                       {
                           mcard.CardNo = jcard["newcardno"].ToString();
                           mcard.IsBind = false;
                           mcard.UnBindTime = DateTime.Now;
                           await _memberCard.UpdateAsync<ICasaMielSession>(mcard).ConfigureAwait(false);
                       }
                       mcard = await _memberCard.FindAsyncByCardnoMobile<ICasaMielSession>(jcard["newcardno"].ToString(), mobile).ConfigureAwait(false);
                       if (mcard == null)
                       {
                           mcard = new MemberCard();
                           mcard.CardNo = jcard["newcardno"].ToString();
                           mcard.Mobile = mobile;
                           mcard.IsBind = true;
                           mcard.CardType = "1";
                           mcard.State = 1;
                           mcard.BindTime = DateTime.Now;
                           mcard.CreateTime = DateTime.Now;
                           await _memberCard.AddAsync<ICasaMielSession>(mcard);
                           var logdata = new UserLog { Url = Request.GetAbsoluteUri(), OPInfo = $"补会员卡,原卡号:[{item.CardNo}，新卡号：{mcard.CardNo}", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
                           await _userLog.AddAsync<ICasaMielSession>(logdata);
                       }

                       var czmodel = await _iicApiService.GetCardBalance(mcard.CardNo).ConfigureAwait(false);
                       // _cacheService.Remove(Constant.MYCARDS_PREFIX + mobile);
                       if (czmodel.code == 0 || czmodel.code == 8)
                       {
                           var cardinfo = JsonConvert.DeserializeObject<JObject>(czmodel.content);
                           cardlist.Add(new CardInfoResponse
                           {
                               cardno = mcard.CardNo,
                               totalmoney = rnt == null ? "0" : cardinfo["totalmoney"].ToString(),
                               cardtype = item.CardType,
                               state = item.State.ToString(),
                               othermoney = rnt == null ? "0" : cardinfo["othermoney"].ToString(),
                               directmoney = rnt == null ? "0" : cardinfo["directmoney"].ToString(),
                               point = rnt == null ? "0" : cardinfo["point"].ToString()
                           });
                       }

                   }
               }
               else
               {
                   cardlist.Add(new CardInfoResponse
                   {
                       cardno = item.CardNo,
                       state = item.State.ToString(),
                       totalmoney = "0",
                       cardtype = item.CardType,
                       othermoney = "0",
                       directmoney = "0",
                       point = "0"
                   });
               }
           }
           var result = new BaseResult<List<CardInfoResponse>>(cardlist, 0, "");
           return Ok(result);
*/
            #endregion

        }

        /// <summary>
        /// 会员卡余额
        /// </summary>
        /// <param name="token">用户token</param>
        /// <param name="req">卡信息</param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> GetBalance([FromBody] CardReq req,
        [FromHeader(Name = "u-token")]  string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }
            var hascard = await HasCard(token, req.cardno).ConfigureAwait(false);
            if (!hascard) {
                return new JsonResult(new { code = -7, content = "", msg = "无此卡" });
            }
            var zmodel = await _iicApiService.GetCardBalance(req.cardno, $"{LoginInfo.Item3}099".ToInt32(0)).ConfigureAwait(false);
            return Ok(zmodel);
        }

        /// <summary>
        /// 消费码
        /// </summary>
        /// <param name="token">用户token</param>
        /// <param name="card">卡信息</param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<BaseResult<ConsumecodeRsp>> Getconsumecode([FromBody]CardReq card, [FromHeader(Name = "u-token")]  string token)
        {
            if (card == null) {
                throw new ArgumentNullException(nameof(card));
            }
            ConsoleHelper.DoLog(card, Request);
            var hascard = await HasCard(token, card.cardno).ConfigureAwait(false);
            if (!hascard) {
                return new BaseResult<ConsumecodeRsp>(null, -7, "无此卡");
               // return new JsonResult(new { code = -7, content = "", msg = "无此卡" });
            }
            var zmodel = await _iicApiService.Geticconsumecode(card.cardno, $"{LoginInfo.Item3}099".ToInt32(0)).ConfigureAwait(false);
            if (zmodel.code == 0) {
                var rnt = JsonConvert.DeserializeObject<ConsumecodeRsp>(zmodel.content);
                return new BaseResult<ConsumecodeRsp>(rnt, 0, zmodel.msg);
            }
            return new BaseResult<ConsumecodeRsp>(null, zmodel.code, zmodel.msg);
        //    var n = new { code = zmodel.code, content = rnt, msg = zmodel.msg };
        //    return new JsonResult(n);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="token"></param>
        /// <param name="cardno"></param>
        /// <returns></returns>
        private async Task<bool> HasCard(string token, string cardno)
        {
            var mobile = MemberHelper.GetMobile(token);
            var list = await _memberCard.GetListAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            if (list == null) {
                return false;
            }
            if (!list.Any(c => c.CardNO.Contains(cardno, StringComparison.CurrentCultureIgnoreCase) && c.IsBind == true)) {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 检查会员消费码处理状态
        /// </summary>
        /// <param name="token">用户token</param>
        /// <param name="card">卡信息（cardno,consumecode</param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<BaseResult<CheckConsumecodeRsp>> Checkconsumecode([FromBody] CheckConsumecodeReq card, [FromHeader(Name = "u-token")]  string token)
        {
            if (card == null) {
                throw new ArgumentNullException(nameof(card));
            }

            var mobile = MemberHelper.GetMobile(token);
            ConsoleHelper.DoLog(card, Request);
            var hascard = await HasCard(token, card.cardno).ConfigureAwait(false);
            if (!hascard) {
                return new BaseResult<CheckConsumecodeRsp>(null, -7, "无此卡");
               // return new JsonResult(new { code = -7, content = "", msg = "无此卡" });
            }
            var command = new CheckConsumeCodeCommand(mobile, card.cardno, card.consumecode,LoginInfo.Item3) { RequestUrl = Request.GetShortUri(), UserIP = Request.GetUserIp() };
            var result = await _mediator.Send(command).ConfigureAwait(false);
            if (result.code == 0) {
                var rnt = JsonConvert.DeserializeObject<CheckConsumecodeRsp>(result.content);
                return new BaseResult<CheckConsumecodeRsp>(rnt,result.code,result.msg);
            }
            if (result.code == 301) {
                var rnt = JsonConvert.DeserializeObject<CheckConsumecodeRsp>(result.content);
                return new BaseResult<CheckConsumecodeRsp>(rnt, result.code, result.msg);
            }
           // return Ok(new { code = result.code, content = rnt, msg = result.msg });
            return new BaseResult<CheckConsumecodeRsp>(null, result.code, result.msg);
            //var a = await _iicApiService.icconsumecheck(card.cardno, card.consumecode).ConfigureAwait(false);

            //         var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
            //         var n = new { code = a.code, content = rnt, msg = a.msg };
            //         if (rnt != null)
            //         {
            //             var je = rnt["money"].ToDecimal(-1);
            //             if (je > 0 && a.code == 301)
            //             {
            //                 var s = _cacheService.Get<string>(Constant.CONSUMECODE + card.consumecode);
            //                 if (string.IsNullOrEmpty(s))
            //                 {
            //                     _cacheService.Add(Constant.CONSUMECODE + card.consumecode, card.consumecode, TimeSpan.FromMinutes(1));
            //                     var logdata = new UserLog { Url = Request.GetAbsoluteUri(), OPInfo = $"扫码支付,卡号:[{card.cardno}],支付码[{card.consumecode}]，支付金额{je}", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
            //                     await _userLog.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
            //                 }
            //             }
            //         }
            //         return new JsonResult(n);
        }
        /// <summary>
        /// 会员绑卡
        /// </summary>
        /// <returns>The test.</returns>
        /// <param name="command">Command.</param>
        /// <param name="token"></param>
        [HttpPost]
        [Route("[action]")]
        public async Task<ActionResult<Zmodel>> MemberBindCard([FromBody] BindMemberCardCommand command, [FromHeader(Name = "u-token")]  string token)
        {
            if (command == null) {
                throw new ArgumentNullException(nameof(command));
            }
            var mobile = MemberHelper.GetMobile(token);
            if (mobile != command.Mobile) {
                return new Zmodel { code = -17, msg = "手机号不符" };
            }
            command.UserIP = Request.GetUserIp();
            command.RequestUrl = Request.GetShortUri();
            command.Source = 15;
            var result = await _mediator.Send(command).ConfigureAwait(false);
            return result;
        }

        /// <summary>
        /// 解绑会员卡
        /// </summary>
        /// <returns>The unbind.</returns>
        /// <param name="command">Command.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<ActionResult<Zmodel>> MemberUnicregist([FromBody] UnBindMemberCardCommand command, [FromHeader(Name = "u-token")] string token)
        {
            if (command == null) {
                throw new ArgumentNullException(nameof(command));
            }
            var mobile = MemberHelper.GetMobile(token);
            command.Mobile = mobile;
            command.UserIP = Request.GetUserIp();
            command.RequestUrl = Request.GetShortUri();
            command.Source = LoginInfo.Item3;
            var result = await _mediator.Send(command).ConfigureAwait(false);
            return result;
        }
        #region MyRegion


        /*
        /// <summary>
        /// 会员绑卡
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> MemberBindCard([FromBody] BindCardDto data, [FromHeader(Name = "u-token")]  string token)
        {
            ConsoleHelper.DoLog(data, Request);
            var mobile = MemberHelper.GetMobile(token);
            if (mobile != data.mobile)
            {
                return new JsonResult(new { code = "-17", msg = "手机号不符" });
            }
            var sucess = await _mobileCheckCode.CheckSmsCodeAsync(data.mobile, data.yzm, true).ConfigureAwait(false);

            if (sucess["code"].ToString() != "0")
            {
                return new JsonResult(sucess);
            }
            //_cacheService.Remove(Constant.MYCARDS_PREFIX + mobile);

            var mcards = await _memberCard.GetCardListAsyncByMobile<ICasaMielSession>(data.mobile).ConfigureAwait(false);
            var content = "";
            if (mcards == null)
            {
                var memberInfo = await _memberService.FindAsync<ICasaMielSession>(mobile);
                if (memberInfo.Source == 1)
                {

                }
                var bandcard = await _iicApiService.Icregist(data.cardno, data.mobile).ConfigureAwait(false);
                if (bandcard != null)
                {
                    content = bandcard.content;
                    if (bandcard.code == 0 || bandcard.code == 101 || bandcard.code == 103)
                    {
                        var mcard = new MemberCard
                        {
                            CardNo = data.cardno,
                            Mobile = data.mobile,
                            IsBind = true,
                            CardType = "1",
                            BindTime = DateTime.Now,
                            CreateTime = DateTime.Now,
                            State = 1
                        };
                        try
                        {
                            await _memberCard.AddAsync<ICasaMielSession>(mcard);
                        }
                        catch (SqlException ex)
                        {
                            if (ex.Number != 2627)
                            {
                                throw ex;
                            }
                        }

                    }
                    else
                    {
                        return new JsonResult(new { code = bandcard.code, msg = bandcard.msg });
                    }
                }
                else
                {
                    return new JsonResult(new { code = "-1", msg = "抱歉，请重试" });
                }
            }
            else
            {
                var list = mcards.Where(c => c.CardType != "3" && c.IsBind == true);
                if (list.Count() > 0)
                {
                    return new JsonResult(new { code = "-1", msg = "您已经绑过卡" });
                }
                var entity = await _memberCard.FindAsyncByCardnoMobile<ICasaMielSession>(data.cardno, mobile);
                var bandcard = await _iicApiService.Icregist(data.cardno, data.mobile);
                if (bandcard != null)
                {
                    content = bandcard.content;
                    if (bandcard.code == 0 || bandcard.code == 101 || bandcard.code == 103)
                    {
                        if (entity == null)
                        {
                            entity = new MemberCard
                            {
                                CardNo = data.cardno,
                                Mobile = data.mobile,
                                IsBind = true,
                                BindTime = DateTime.Now,
                                CardType = "1",
                                CreateTime = DateTime.Now,
                                State = 1
                            };

                            try
                            {
                                await _memberCard.AddAsync<ICasaMielSession>(entity);
                            }
                            catch (SqlException ex)
                            {
                                if (ex.Number != 2627)
                                {
                                    throw ex;
                                }
                            }
                            //await _memberCard.UnitOfWork.SaveEntitiesAsync();
                        }
                        else
                        {
                            entity.IsBind = true;
                            entity.BindTime = DateTime.Now;
                            await _memberCard.UpdateAsync<ICasaMielSession>(entity);
                        }
                    }
                    else
                    {
                        return new JsonResult(new { code = bandcard.code, msg = bandcard.msg });
                    }
                }
                var logdata = new UserLog { Url = Request.GetAbsoluteUri(), OPInfo = $"绑会员卡,卡号:[{data.cardno}]", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
                await _userLog.AddAsync<ICasaMielSession>(logdata);

            }
            return new JsonResult(new { code = 0, content = content, msg = "绑卡成功！" });


            //var mcards = await _memberCard.GetCardListAsyncByMobile(data.mobile);

            //if (mcards == null)
            //{
            //    var bandcard = await _iicApiService.Icregist(data.cardno, data.mobile);
            //    if (bandcard != null)
            //    {
            //        if (bandcard.code == 0 || bandcard.code == 101 || bandcard.code == 103)
            //        {
            //            var mcard = new MemberCard();
            //            mcard.CardNo = data.cardno;
            //            mcard.Mobile = data.mobile;
            //            mcard.IsBind = true;
            //            mcard.BindTime = DateTime.Now;
            //            mcard.CreateTime = DateTime.Now;
            //            _memberCard.Add(mcard);
            //            await _memberCard.UnitOfWork.SaveEntitiesAsync();
            //        }
            //        else
            //        {
            //            return new JsonResult(new { code = bandcard.code, msg = bandcard.msg });
            //        }
            //    }
            //    else
            //    {
            //        return new JsonResult(new { code = "999", msg = "抱歉，请重试" });
            //    }
            //}
            //else
            //{
            //    var list = mcards.Where(c => c.IsBind == true);
            //    if (list.Count() > 0)
            //    {
            //        if (list.Where(c => c.CardNo == data.cardno).Count() == 1)
            //        {
            //            var bandcard = await _iicApiService.Icregist(data.cardno, data.mobile);
            //            if (bandcard != null)
            //            {
            //                if (bandcard.code == 0 || bandcard.code == 101 || bandcard.code == 103)
            //                {
            //                    return new JsonResult(new { code = 0, content = "", msg = "绑卡成功！" });
            //                }
            //                else
            //                {
            //                    return new JsonResult(new { code = bandcard.code, msg = bandcard.msg });
            //                }
            //            }
            //            else
            //            {
            //                return new JsonResult(new { code = "999", msg = "抱歉，请重试" });
            //            }
            //        }
            //    }
            //    var mc = mcards.Where(c => c.CardNo == data.cardno).FirstOrDefault();
            //    if (mc == null)
            //    {
            //        var bandcard = await _iicApiService.Icregist(data.cardno, data.mobile);// await _iicApiService.Icregist(data.cardno, data.mobile);
            //        if (bandcard != null)
            //        {
            //            //8、未使用 101指定手机(微信)号已绑定
            //            //103微信(手机)号和IC卡已解决绑定
            //            if (bandcard.code == 0 || bandcard.code == 101 || bandcard.code == 103)
            //            {
            //                mc = new MemberCard();
            //                mc.CardNo = data.cardno;
            //                mc.Mobile = data.mobile;
            //                mc.IsBind = true;
            //                mc.BindTime = DateTime.Now;
            //                mc.CardType = "1";
            //                mc.CreateTime = DateTime.Now;
            //                _memberCard.Add(mc);
            //                await _memberCard.UnitOfWork.SaveEntitiesAsync();
            //            }
            //            else
            //            {
            //                return new JsonResult(new { code = bandcard.code, msg = bandcard.msg });
            //            }
            //        }
            //    }
            //    else
            //    {
            //        var bandcard = await _iicApiService.Icregist(data.cardno, data.mobile);
            //        if (bandcard != null)
            //        {
            //            //8、未使用 101指定手机(微信)号已绑定
            //            if (bandcard.code == 0 || bandcard.code == 101 || bandcard.code == 103)
            //            {
            //                mc.IsBind = true;
            //                mc.BindTime = DateTime.Now;
            //                _memberCard.Update(mc);
            //                await _memberCard.UnitOfWork.SaveChangesAsync();
            //            }
            //            else
            //            {
            //                return new JsonResult(new { code = bandcard.code, msg = bandcard.msg });
            //            }
            //        }
            //    }
            //}
            //var logdata = new UserLog { Url = Request.GetAbsoluteUri(), OPInfo = $"绑会员卡,卡号:[{data.cardno}]", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
            //_userLog.Add(logdata);
            //return new JsonResult(new { code = 0, content = "", msg = "绑卡成功！" });
        }
        /// <summary>
        /// 解绑会员卡
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> MemberUnicregist([FromBody] MemberUnicCard data, [FromHeader(Name = "u-token")] string token)
        {
            ConsoleHelper.DoLog(data, Request);
            var mobile = MemberHelper.GetMobile(token);
            var sucess = await _mobileCheckCode.CheckSmsCodeAsync(mobile, data.yzm, false);
            if (sucess["code"].ToString() != "0")
            {
                return new JsonResult(sucess);
            }
            // var mcard = _context.MemberCard.FirstOrDefault(c => c.Mobile == mobile && c.IsBind == true);
            var mcard = await _memberCard.FindAsyncByCardnoMobile<ICasaMielSession>(data.cardno, mobile);
            if (mcard == null)
            {
                //return BadRequest();
                return new JsonResult(new { code = -16, content = "", msg = "会员卡已经解绑" });
            }
            if (mcard.CardNo != data.cardno)
            {
                return new JsonResult(new { code = -10, content = "", msg = "卡号不存在" });
            }
            if (mcard.CardType == "2")
            {
                var result = await _iicApiService.GetCardBalance(data.cardno);
                if (result.code == 0)
                {
                    var vc = JsonConvert.DeserializeObject<JObject>(result.content);
                    if (Convert.ToDecimal(vc["directmoney"].ToString()) > 0)
                    {
                        return new JsonResult(new { code = -11, content = "", msg = "卡内有余额不能解绑！" });
                    }

                    //                "totalmoney": 598.01,
                    //"directmoney": 598.01,
                    //"othermoney": 0,
                }
            }
            var a = await _iicApiService.Unicregist(data.cardno, mcard.Mobile);
            var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
            if (a.code == 0 || a.code == 103)//14手机号和会员卡号不匹配(已解）
            {
                mcard.IsBind = false;
                mcard.UnBindTime = DateTime.Now;
                await _memberCard.UpdateAsync<ICasaMielSession>(mcard);
                //await _memberCard.UnitOfWork.SaveChangesAsync();
                // _cacheService.Remove(Constant.MYCARDS_PREFIX + mobile);
                var logdata = new UserLog { Url = Request.GetAbsoluteUri(), OPInfo = $"解绑会员卡,卡号:[{data.cardno}]", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
                await _userLog.AddAsync<ICasaMielSession>(logdata);
                return new JsonResult(new { code = 0, content = "", msg = "解绑成功！" });
            }

            var n = new { code = a.code, content = rnt, msg = a.msg };
            return new JsonResult(n);
        }
        */
        #endregion


        /// <summary>
        /// 注册虚拟会员卡
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> Icselfregist([FromHeader(Name = "u-token")] string token)
        {
            var mobile = MemberHelper.GetMobile(token);
            var mcards = await _memberCard.GetListAsync<ICasaMielSession>(mobile).ConfigureAwait(false);// _context.MemberCard.Where(c => c.Mobile == mobile).ToList();
            var list = mcards.Where(c => c.IsBind == true && (c.CardType == "1" || c.CardType == "2"));
            if (list.Any()) {
                return new JsonResult(new { code = -12, msg = "您已经有会员卡，无需注册会员卡" });
            }
            var memberInfo = await _memberService.FindAsync<ICasaMielSession>(mobile).ConfigureAwait(false);

            var newcard = await _iicApiService.Icselfregist(mobile, $"{LoginInfo.Item3}099".ToInt32(0)).ConfigureAwait(false);
            var jobj = JsonConvert.DeserializeObject<JObject>(newcard.content);
            if (newcard.code == 0) {
                var mcard = new MemberCard {
                    CardNO = jobj["cardno"].ToString(),
                    M_ID = memberInfo.ID,
                    Mobile = mobile,
                    CardType = "2",
                    IsBind = true,
                    BindTime = DateTime.Now,
                    CreateTime = DateTime.Now,
                    Source = 15
                };
                await _memberCard.AddAsync<ICasaMielSession>(mcard).ConfigureAwait(false);
                //await _memberCard.UnitOfWork.SaveEntitiesAsync();
                return new JsonResult(new { code = 0, data = new { CardNo = mcard.CardNO, CardType = mcard.CardType }, msg = "会员卡注册成功" });
            } else {
                var n = new { code = newcard.code, content = jobj, msg = newcard.msg };
                return new JsonResult(n);
            }
        }
        ///// <summary>
        ///// 注册新会员测试用
        ///// </summary>
        ///// <param name="data"></param>
        ///// <param name="token"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[Route("[action]")]
        //[ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        //[ProducesResponseType((int)HttpStatusCode.NotFound)]
        //public async Task<IActionResult> Icselfregist([FromBody] UnicCard data, [FromHeader(Name = "u-token")] string token)
        //{
        //    var a = await _iicApiService.Icselfregist(data.mobile);
        //    var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
        //    var n = new { code = a.code, content = rnt, msg = a.msg };
        //    return new JsonResult(n);
        //}

        /// <summary>
        /// 会员申请会员卡
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> MemberIcselfregist([FromHeader(Name = "u-token")] string token)
        {
            var mobile = MemberHelper.GetMobile(token);
            var command = new MemberIcselfregistCommand(mobile, $"{LoginInfo.Item3}099".ToInt32(0)) { RequestUrl = Request.GetShortUri(), UserIP = Request.GetUserIp() };
            var commandresult = await _mediator.Send(command).ConfigureAwait(false);
            return Ok(commandresult);
            //var cardlist = await _memberCard.GetCardListAsyncByMobile<ICasaMielSession>(mobile);// _context.MemberCard.Where(c => c.Mobile == mobile && c.IsBind == true);
            //if (cardlist.Where(c => c.IsBind == true && c.CardType != "3").Count() > 0)
            //{
            //    return new JsonResult(new { code = -12, msg = "已有会员卡不能再申请" });
            //}
            //var result = await _iicApiService.Icselfregist(mobile);
            //var rnt = JsonConvert.DeserializeObject<JObject>(result.content);
            //if (result.code == 0)
            //{
            //    var mcard = await _memberCard.FindAsyncByCardnoMobile<ICasaMielSession>(rnt["cardno"].ToString(), mobile);
            //    logger.Trace($"新用户注册{mobile}会员卡，卡号[{ rnt["cardno"].ToString()}]");
            //    //_cacheService.Remove(Constant.MYCARDS_PREFIX + mobile);
            //    if (mcard == null)
            //    {
            //        mcard = new MemberCard
            //        {
            //            CardNO = rnt["cardno"].ToString(),
            //            Mobile = mobile,
            //            IsBind = true,
            //            CardType = "2",
            //            BindTime = DateTime.Now,
            //            CreateTime = DateTime.Now
            //        };
            //        try
            //        {
            //            await _memberCard.AddAsync<ICasaMielSession>(mcard);
            //        }
            //        catch (SqlException ex)
            //        {
            //            if (ex.Number != 2627)
            //            {
            //                throw ex;
            //            }
            //        }
            //    }
            //    else
            //    {
            //        mcard.IsBind = true;
            //        mcard.BindTime = DateTime.Now;
            //        await _memberCard.UpdateAsync<ICasaMielSession>(mcard);
            //    }
            //    var logdata = new UserLog { Url = Request.GetAbsoluteUri(), OPInfo = $"申请会员卡,卡号:[{rnt["cardno"].ToString()}]", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
            //    await _userLog.AddAsync<ICasaMielSession>(logdata);
            //    return new JsonResult(new { code = 0, msg = "会员卡申请成功", cardno = mcard.CardNO });
            //}
            //var n = new { code = result.code, content = rnt, msg = result.msg };
            //return new JsonResult(n);
        }

        /// <returns></returns>
        /// <summary>
        /// 查询会员卡消费和充值记录
        /// </summary>
        /// <remarks>
        /// {
        /// "code": 0,
        /// "content": [
        ///   {
        ///      "wxopenid": "",
        ///      "cardno": "276523218",
        ///     "shopid": "1",
        ///      "shopname": "玫隆皇冠测试",
        ///      "recdate": "2017-12-27 10:25:22",
        ///      "consumetype": "充值",
        ///      "tradeno": "C13S1G58221",
        ///      "totalmoney": 100,
        ///      "discountmoney": 0,
        ///      "realpaymoney": 100,
        ///      "directmoney": 100,
        ///      "othermoney": 0,
        ///      "point": 0
        ///    },
        ///    {
        ///      "wxopenid": "",
        ///      "cardno": "276523218",
        ///      "shopid": "1",
        ///      "shopname": "玫隆皇冠测试",
        ///      "recdate": "2017-12-27 10:25:36",
        ///      "consumetype": "充值",
        ///      "tradeno": "C13S1G58222",
        ///     "totalmoney": 100,
        ///      "discountmoney": 0,
        ///      "realpaymoney": 100,
        ///      "directmoney": 100,
        ///     "othermoney": 0,
        ///      "point": 0
        ///   },
        ///   {
        ///      "wxopenid": "",
        ///      "cardno": "276523218",
        ///      "shopid": "1",
        ///      "shopname": "玫隆皇冠测试",
        ///     "recdate": "2017-12-27 10:35:55",
        ///      "consumetype": "充值",
        ///      "tradeno": "C13S1G58223",
        ///      "totalmoney": 100,
        ///      "discountmoney": 0,
        ///      "realpaymoney": 100,
        ///     "directmoney": 100,
        ///      "othermoney": 0,
        ///      "point": 0
        ///    }
        /// ],
        ///  "msg": "处理成功"
        ///}
        ///</remarks>
        /// <param name="token">用户token</param>
        ///<param name="data">cardInfo</param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(ZmodelExt), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> GetICRecord([FromBody]IcRecordqueryReq data, [FromHeader(Name = "u-token")]  string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            var mobile = MemberHelper.GetMobile(token);
            data.Enddate = DateTime.Now.AddMinutes(10);
            var mcard = await _memberCard.GetListAsync<ICasaMielSession>(mobile).ConfigureAwait(false);

            if (mcard == null || !mcard.Any(c => c.IsBind == true)) {
                return new JsonResult(new { code = -7, content = "", msg = "无此卡" });
            }
            var a = await _iicApiService.IcRecordQuery(data).ConfigureAwait(false);
            return Ok(a);

        }


        /// <summary>
        /// 二维码查询
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>

        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> icqrcodequery([FromBody]IcQrcodeChargeReq data, [FromHeader(Name = "u-token")]  string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            var mobile = MemberHelper.GetMobile(token);
            var zmodel = await _iicApiService.IcQrcodeQuery(data.Cardno, mobile, data.Qrcode).ConfigureAwait(false);
            var rnt = JsonConvert.DeserializeObject<JObject>(zmodel.content);
            var n = new { code = zmodel.code, content = rnt, msg = zmodel.msg };
            return new JsonResult(n);
        }
        /// <summary>
        /// 二维码使用
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> icqrcodeverify([FromBody]IcQrcodeChargeReq data, [FromHeader(Name = "u-token")]  string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            var mobile = MemberHelper.GetMobile(token);
            var command = new GiftCardReChargeCommand(data.Cardno, data.Qrcode,mobile, $"{LoginInfo.Item3}099".ToInt32(0)) { RequestUrl = Request.GetShortUri(), UserIP = Request.GetUserIp() };
            var result = await _mediator.Send(command).ConfigureAwait(false);
            return Ok(result);
            #region MyRegion
            /*
            var mcard = await _memberCard.GetCardListAsyncByMobile<ICasaMielSession>(mobile);

            string cardno = "";
            var ar = mcard.Where(c => c.CardType == "3").SingleOrDefault();
            if (ar != null)
            {
                cardno = ar.CardNo;
            }
            logger.Trace($"icqrcodeverifyReq:{cardno}||{mobile}||{data.qrcode}");
            var send = await _mobileCheckCode.CheckSmsCodeAsync(mobile, data.yzm, true);
            if (send["code"].ToInt16(-5) < 0)
            {
                return new JsonResult(send);
            }


            var zmodel = await _iicApiService.icqrcodeverify(cardno, mobile, data.qrcode);
            logger.Trace($"icqrcodeverifyResult:{JsonConvert.SerializeObject(zmodel)}");

            if (zmodel.code == 0)
            {
                if (cardno == "")
                {
                    var rnt = JsonConvert.DeserializeObject<JObject>(zmodel.content);
                    cardno = rnt["cardno"].ToString();
                    ar = new MemberCard
                    {
                        CardNo = cardno,
                        CardType = "3",
                        IsBind = true,
                        BindTime = DateTime.Now,
                        CreateTime = DateTime.Now,
                        Mobile = mobile
                    };
                    await _memberCard.AddAsync<ICasaMielSession>(ar);
                }
                await _userLog.AddAsync<ICasaMielSession>(new UserLog { OPInfo = "礼品卡充值,卡号:[" + cardno + "],qrcode:" + data.qrcode, UserName = mobile, Url = Request.GetAbsoluteUri(), UserIP = Request.GetUserIp(), OPTime = DateTime.Now });
            }

            // _cacheService.Remove(Constant.MYCARDS_PREFIX + mobile);
            return new JsonResult(zmodel);
            */
            #endregion
        }

        /// <summary>
        /// 实体卡调整状态
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> icrealcardadjust([FromBody]CardStateReq data, [FromHeader(Name = "u-token")]string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            var mobile = MemberHelper.GetMobile(token);
            data.Phoneno = mobile;
            var zmodel = await _iicApiService.IcRealCardAdjust(data).ConfigureAwait(false);
            var entity = await _memberCard.FindAsync<ICasaMielSession>(data.Cardno, mobile).ConfigureAwait(false);
            logger.Trace($"icrealcardadjust:{JsonConvert.SerializeObject(entity)}");
            if (entity != null) {
                if (zmodel.code == 0) {
                    entity.State = data.State;
                    await _memberCard.UpdateAsync<ICasaMielSession>(entity).ConfigureAwait(false);
                    var logdata = new UserLog { Url = Request.GetShortUri(), OPInfo = $"实体卡调整状态,卡号:[{data.Cardno}],状态：{data.State}", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
                    await _mediator.Publish(new UserLogNoticeCommand(logdata)).ConfigureAwait(false);
                   // await _userLog.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
                }
            }
            return Ok(zmodel);
        }
    }
}